package com.demo.java.concurrent;

import org.junit.Test;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

public class AQSTest {

    static class MyLock extends AbstractQueuedSynchronizer {

        protected boolean tryAcquire(int arg) {
            if (compareAndSetState(0, 1)) {
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        public void lock() {
            acquire(1);
        }

        @Override
        protected boolean tryRelease(int arg) {
            if (compareAndSetState(1, 0)) {
                setExclusiveOwnerThread(null);
                return true;
            }
            return false;
        }

        public void unlock() {
            release(1);
        }

        @Override
        protected boolean isHeldExclusively() {
            return getExclusiveOwnerThread() == Thread.currentThread();
        }

        public boolean isLocked() {
            return getState() != 0;
        }
    }

    @Test
    public void lockTest() {
        MyLock lock = new MyLock();

        lock.lock();
        lock.lock();

        System.out.println("===== locked");

        lock.unlock();
    }
}
